package com.hx.er.common.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.hx.er.bean.base.UserBean;
import com.hx.er.common.entity.ErBehaviorEntity;
import com.hx.er.common.logic.BehaviorManager;
import com.hx.er.common.system.Constants;
import com.hx.er.common.system.ErRestraurant;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ActionMethodInterceptor extends AbstractInterceptor {

	// 序列化ID
	private static final long serialVersionUID = 9164489404585238463L;

	private static Logger logger = Logger.getLogger(ActionMethodInterceptor.class);

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		// 行为对象
		ErBehaviorEntity behavior = new ErBehaviorEntity();

		// 设置用户信息
		UserBean userBean = (UserBean) ai.getInvocationContext().getSession().get(Constants.SESSION_USER_INFO);

		// 方法执行，返回
		String returnString = null;
		if (userBean == null) {
			behavior.setUserId(0);
		} else {
			behavior.setUserId(userBean.getUserId());
		}

		// 取出域名、餐馆ID
		String currentServerName = ((HttpServletRequest) ai.getInvocationContext().get(ServletActionContext.HTTP_REQUEST)).getServerName();
		if (ErRestraurant.getRestByServerName(currentServerName) != null) {
			behavior.setRestId(ErRestraurant.getRestByServerName(currentServerName).getRestId());
		} else {
			behavior.setRestId(0);
		}

		// 设置行为
		behavior.setMethodName(ai.getProxy().getConfig().getMethodName());
		behavior.setActionName(ai.getProxy().getConfig().getClassName());

		try {
			// 打印日志
			logger.debug("[MethodInterceptor]" + ai.getProxy().getConfig().getMethodName() + "[BEGIN]");
			behavior.setStartTime(System.currentTimeMillis());
			returnString = ai.invoke();
			logger.debug("[MethodInterceptor]" + ai.getProxy().getConfig().getMethodName() + "[END]");
			behavior.setResult(true);
		} catch (Exception e) {
			logger.debug("[MethodInterceptor]" + ai.getProxy().getConfig().getMethodName() + "[EXCEPTION]");
			behavior.setResult(false);
			e.printStackTrace();
		} finally {
			behavior.setEndTime(System.currentTimeMillis());
			BehaviorManager.getInstance().append(behavior);
		}

		// 返回
		return returnString;
	}

}
